package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;	

import parameter.GetParameter;

public class KeywordCodeTranslator {

	/**
	 * 从keywords table 读出keyword列的数据，翻译成utf-8和gbk格式分别写入utf-8和gbk
	 */
	int workingSourceId = 0;
	
	public int translateKeywords() {
		// translateSuccess作为成功执行的标记，指明这部分功能执行过啦。
		final int translateSuccess = 2;
		
		Connection conn = null;
		Statement stmt = null;
		Statement stmtAdd = null;
		ResultSet rs = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://" + dBhost + "/" + dBName, "root", "");
			stmt = conn.createStatement();
			rs = stmt.executeQuery("select id, keyword from keywords where id > " + translateBeginner);
			//System.out.println(gp.getKeywordcode());
			//System.out.println(gp.getKeywordCodeTranslatDBfieldName());
			//System.out.println();
			while(rs.next())
			{
				workingSourceId = rs.getInt("id");
				stmtAdd = conn.createStatement();
				stmtAdd.execute("update keywords set kwEng = '" + URLEncoder.encode(rs.getString("keyword"),"UTF-8") + "' where id = " + rs.getInt("id"));
				stmtAdd.execute("update keywords set gbk = '" + URLEncoder.encode(rs.getString("keyword"),"gbk") + "' where id = " + rs.getInt("id"));
				System.out.println(rs.getString("keyword") + "译码完成");
			}		
		} catch (ClassNotFoundException e) {
			//--------e.printStackTrace();----------
			this.processException();
			System.out.println("数据库驱动没有找到或出错");
		} catch (SQLException e) {
			this.processException();
			e.printStackTrace();	
		} catch (UnsupportedEncodingException e) {
			this.processException();
			e.printStackTrace();
		
		}finally {
			try {
				if(rs != null) {
					rs.close();
					rs = null;
				}
				if(stmt != null) {
					stmt.close();
					stmt = null;
				}
				if(conn != null) {
					conn.close();
					conn = null;
				}
				if(stmtAdd != null) {
					stmtAdd.close();
					stmtAdd = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return translateSuccess;
	}
	//catch Exception的处理方法，收集到现在进行到的keywords表中id号，下次从这个开始运行
	public void processException(){
		
		System.out.println("进行keywords翻译时出错，现在进行到keywords表中的第" + workingSourceId + "个数据");
		GetParameter gp = new GetParameter();
		gp.setTranslateBeginner(workingSourceId);
	}
	
	String dBhost = null;
	String dBName = null;
	int translateBeginner = 0;
	public void setdBhost(String dBhost) {
		this.dBhost = dBhost;
	}
	public void setdBName(String dBName) {
		this.dBName = dBName;
	}
	public void setTranslateBeginner(int translateBeginner) {
		this.translateBeginner = translateBeginner;
	}

	
	
}
